import re
from django import http
from django.contrib.auth import authenticate, login, logout
from django.core.mail import send_mail
from django.http import HttpResponse, HttpResponsePermanentRedirect
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views import View
from boxuegu import settings
from users import constants
from users.forms import ForgetForm
from users.models import UserProfile
from utils.mixin_utils import LoginRequiredMixin
from . import constants, signature
from django.contrib.auth import logout
from utils.mixin_utils import LoginRequiredMixin


# 由于开发进度不统一，
# 为了能运行，以下是临时代码

class UserLogout(View):
    def get(self, request):
        # 删除状态保持
        logout(request)
        # 删除cookie中的username
        response = redirect('/login/')
        response.delete_cookie('username')
        return response


class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'usercenter-info.html')


class LoginView(View):
    '''用户登入'''

    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 认证登录用户
        # TODO 增加 request
        user = authenticate(request, username=username, password=password)

        if user is None:
            # 用户名或密码错误
            # return HttpResponse("用户名或密码错误")
            return render(request, 'login.html', {'msg': '用户名或密码错误'})

        else:
            # 用户名或密码正确
            login(request, user)
            username = user.username
            response = redirect('/info/')
            response.set_cookie('username', username, max_age=constants.USERNAME_COOKIE_EXPIRES)

            return response


class ResetView(View):
    # 获取更改密码页面
    def get(self, request, active_code):

        # 接收
        active_code = active_code

        # 验证
        # 处理
        json_dict = signature.loads(active_code, constants.EMAIL_ACTIVE_EXPIRES)

        if not json_dict:
            return render(request, 'active_fail.html')
        user_id = json_dict.get('user_id')

        try:
            user = UserProfile.objects.get(pk=user_id)
        except Exception as e:
            return http.HttpResponseForbidden('用户无效')

        email = user.email  # 响应
        return render(request, 'password_reset.html', {'email': email})

    # 更改数据库中的用户密码，并重定向到登陆页面
    def post(self, request):
        # 接收
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        email = request.POST.get('email')

        # 验证
        if not all([password1, password2]):
            return http.HttpResponseForbidden('缺少密码')
        if not password1 == password2:
            return http.HttpResponseForbidden('两次输入密码不一致')
        if not re.match(r'^[a-zA-Z0-9_-]{6,20}$', password1):
            return http.HttpResponseForbidden('密码格式为：请输入6-20个非中文字符')

        # 处理
        try:
            user = UserProfile.objects.get(email=email)
        except Exception as e:
            return http.HttpResponseForbidden('无此用户')
        user.set_password(password1)
        user.save()

        # logout(request)
        # response = redirect('/login/')
        # response.delete_cookie('username')
        # return response

        # 响应
        return redirect('/login/')


class ForgetPwdView(View):
    '''忘记密码'''

    def get(self, request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    def post(self, request):
        data = request.POST
        email = data.get('email')
        forget_form = ForgetForm(data)
        # 验证图片
        res = forget_form.is_valid()
        # 验证没有通过
        if not res:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})

        # 验证邮箱
        # email = data.get('email')
        try:
            user = UserProfile.objects.get(email=email)
        except:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form, 'msg': '邮箱不存在！'})

        user = UserProfile.objects.get(email=email)
        # 将用户编号加密
        token = signature.dumps({'user_id': user.id}, constants.EMAIL_ACTIVE_EXPIRES)
        # 拼接激活的链接地址
        settings.EMAIL_VERIFY_URL += token

        # 使用标签的方式 包含跳转连接
        # TODO 开 docker 太麻烦，使用传统方式
        # 发送邮件很慢，多等会
        send_mail('博学谷-邮箱找回密码', '', settings.EMAIL_FROM, [email], html_message=settings.EMAIL_VERIFY_URL)
        em = email.split('@')[1]
        from . import emailurl
        url = emailurl.email.get(em)
        if url == None:
            url = '#'

        return render(request, 'send_success.html', {'em': url})


class MyCourseView(View):
    """
    我的课程视图
    """
    pass


class MyfavView(View):
    """
    我的收藏视图
    """
    pass


class MyMessageView(View):
    """
    我的消息
    """
    pass


class ImageView(View):
    """
    图片视图
    """

    def post(self, request):
        """
        修改头像
        :param request:
        :return:
        """
        image_file = request.FILES['image']
        user = request.user
        user.image = image_file
        user.save()
        return redirect('/info/')